const warn = require('./warn');
const DB = require('../db/index');
const Biz = require('../biz/index');
const fw = require('../core/framework');

// 算法根据指标和指标值分析出不同的事件
module.exports = {
    // 分析指标
    analysisIndex(data) {
        let indexData = this.toIndexData(data);
        if (this.isEvent(indexData)) {
            console.log('==================收到事件数据----2------====================');
            this.saveEvent(indexData);
        }
    },
    isEvent(data) {
        let indexName = data.index_name + '';
        switch (indexName) {
            case 'fall': // 跌倒事件
                return true;
            default:
                return false;
        }
    },
    // 数据转义，指标数据清洗
    toIndexData(data) {
        return {
            device_id: data.device_id,
            face_id: data.face_id,
            index_name: data.index_name,
            index_value: data.index_value,
            start_time: data.index_time,
            video_url: data.video_url
        }
    },
    saveAlarmNoticeRecord(data, successFn) {
        Biz.AlarmNoticeRecord.create({
            merchant_id: data.merchant_id,
            alarm_contact_group_id: data.alarm_contact_group_id,
            alarm_event_id: data.alarm_event_id,
            status: data.status
        }, function (AlarmNoticeRecord) {
            if (fw.isFn(successFn)) successFn(AlarmNoticeRecord)
        }, function () {

        })
    },
    findAlarmContactGroupAndUsers(device_id, successFn) {
        let self = this;
        DB.AlarmContactGroupDevice.findByDeviceId({device_id: device_id}).then(AlarmContactGroupDeviceRes => {
            // let AlarmContactGroupDeviceRes = [AlarmContactGroupDeviceResDatas[0]];
            // console.log('查询到的AlarmContactGroupDeviceRes',AlarmContactGroupDeviceRes)
            AlarmContactGroupDeviceRes.forEach(res => {
                let alarm_contact_group_id = res.alarm_contact_group_id;
                DB.AlarmContactGroupUser.findByAlarmContactGroupId({alarm_contact_group_id: alarm_contact_group_id}).then(AlarmContactGroupUserRes => {
                    // let AlarmContactGroupUserRes = [AlarmContactGroupUserResDatas[0]];
                    const keys = Object.keys(AlarmContactGroupUserRes);
                    const users = keys.map((d) => {
                        return DB.User.searchById({id: AlarmContactGroupUserRes[d].user_id});
                    });
                    Promise.all(users).then(userRes => {
                        userRes = JSON.parse(JSON.stringify(userRes));
                        let users = [];
                        userRes.forEach(u => {
                            u.forEach(uu => {
                                users.push(uu);
                            })
                        });
                        if (fw.isFn(successFn)) successFn(alarm_contact_group_id, users);
                    });
                })
            })
        })
    },
    getIndexName(indexName) {
        switch (indexName) {
            case 'fall':
                return '跌倒'
        }
    },
    saveEvent(data) {
        var self = this;
        let _saveEvent = function (eventData) {
            let alarmEventData = {
                merchant_id: eventData.merchant_id,
                device_id: eventData.device_id,
                face_id: eventData.face_id || null,
                index_name: eventData.index_name,
                index_value: eventData.index_value,
                start_time: eventData.start_time,
                end_time: null,
                handle_type: eventData.handle_type || 2,
                video_url: eventData.video_url
            };

            Biz.AlarmEvent.create(alarmEventData, function (alarmEventRes) {
                console.log('日志创建完成，开始查询发送短信');
                self.findAlarmContactGroupAndUsers(eventData.device_id, function (alarm_contact_group_id, users) {
                    let noticeRecordData = {
                        merchant_id: eventData.merchant_id,
                        alarm_contact_group_id: alarm_contact_group_id,
                        alarm_event_id: alarmEventRes.data.id,
                    };
                    let userCount = users.length;
                    let currUserCount = 0;
                    users.forEach(user => {
                        console.log('已发送短信', {
                            mobile: user.mobile,
                            templateData: [eventData.face_name || '有人', eventData.device_name, eventData.start_time, self.getIndexName(eventData.index_name)]
                        });
                        // 发送报警短信
                        warn.send({
                            mobile: user.mobile,
                            templateData: [eventData.face_name  || '有人', eventData.device_name, eventData.start_time, self.getIndexName(eventData.index_name)]
                        }, function () {
                            currUserCount++;
                            if (fw.isEqual(currUserCount, userCount)) {
                                noticeRecordData.status = 1;
                                self.saveAlarmNoticeRecord(noticeRecordData);
                            }
                        }, function () {
                            noticeRecordData.status = 0;
                            self.saveAlarmNoticeRecord(noticeRecordData);
                        })
                    });
                });
            }, function () {
            })
        };
        this.dataToEvent(data, function (eventData) {
            console.log('==================收到事件数据----3------====================', eventData)
            /**
             * 判断该事件是否存在
             * 判断依据
             *  1. 该设备号是否存在事件
             *  2. 该设备号的最后一个事件是否有结束时间
             *  3. 两个数据的开始时间差是否大于60分钟
             *  处理
             *  如果存在结束时间，不处理，不存在结束时间，开始时差小于60分钟不处理，大于60分钟作为新事件
             *  不存在，插入新事件
             */
            let lastEventTerms = {
                device_id: eventData.device_id
            };
            if (eventData.face_id) {
                lastEventTerms.face_id = eventData.face_id;
            }
            Biz.AlarmEvent.getLastEvent(lastEventTerms, function (lastEventData) {
                if (lastEventData.end_time) {
                    _saveEvent(eventData);
                }
                // else{
                //     if(fw.moment(eventData.start_time).diff(fw.moment(lastEventData.start_time),'minute')>60){
                //         _saveEvent(eventData);
                //     }else{
                //         console.log('-----------事件已存在----------------')
                //     }
                // }
            }, function () {
                console.log('==================收到事件数据----4------====================')
                _saveEvent(eventData);
            });
        });
    },
    dataToEvent(data, successFn) {
        console.log('==================收到事件数据----20------====================', data.device_id, data.face_id)
        Biz.Device.getDataById(data.device_id, function (deviceRes) {
            console.log('==================收到事件数据----21------====================', deviceRes)
            if (data.face_id) {
                Biz.Face.getDataById(data.face_id, function (faceRes) {
                    console.log('==================收到事件数据----22------====================', faceRes)
                    successFn({
                        merchant_id: deviceRes.merchant_id,
                        device_id: data.device_id,
                        device_name: deviceRes.name,
                        face_id: data.face_id,
                        face_name: faceRes.name,
                        index_name: data.index_name,
                        index_value: data.index_value,
                        start_time: data.start_time,
                        handle_type: '',
                        video_url: data.video_url || ''
                    })
                }, function () {

                });
            } else {
                successFn({
                    merchant_id: deviceRes.merchant_id,
                    device_id: data.device_id,
                    device_name: deviceRes.name,
                    index_name: data.index_name,
                    index_value: data.index_value,
                    start_time: data.start_time,
                    video_url: data.video_url || ''
                })
            }
        }, function () {
            console.log('==================收到事件数据----201------====================')
        });
    }
};
